<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>微博热搜评论语义分析系统</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <!-- Chart.js -->
    <script src="https://cdn.bootcdn.net/ajax/libs/Chart.js/4.4.0/chart.min.js"></script>
    <!-- WordCloud -->
    <script src="https://cdn.bootcdn.net/ajax/libs/wordcloud2.js/1.2.2/wordcloud2.min.js"></script>
    
    <style>
        body {
            background-color: #f8f9fa;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
        }
        .topic-card {
            transition: transform 0.2s;
            cursor: pointer;
        }
        .topic-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .hot-rank {
            font-size: 1.2em;
            font-weight: bold;
        }
        .heat-badge {
            font-size: 0.8em;
            padding: 0.25em 0.5em;
        }
        .analysis-section {
            display: none;
        }
        .loading {
            display: none;
        }
        .keyword-cloud {
            height: 300px;
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            position: relative;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-dark bg-primary">
        <div class="container-fluid">
            <span class="navbar-brand mb-0 h1">
                <i class="fas fa-fire"></i> 微博热搜评论语义分析系统
            </span>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="row">
            <!-- 热搜榜单 -->
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-list-ol"></i> 实时热搜榜
                        </h5>
                    </div>
                    <div class="card-body">
                        <div id="hot-topics">
                            {% for topic in topics %}
                            <div class="card mb-2 topic-card" data-topic="{{ topic.title }}">
                                <div class="card-body py-2">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <span class="hot-rank text-primary">{{ topic.rank }}</span>
                                            <span class="ms-2">{{ topic.title }}</span>
                                        </div>
                                        <span class="badge bg-danger heat-badge">{{ topic.heat }}</span>
                                    </div>
                                </div>
                            </div>
                            {% endfor %}
                        </div>
                    </div>
                </div>
            </div>

            <!-- 分析结果 -->
            <div class="col-md-8">
                <div id="initial-message" class="text-center py-5">
                    <i class="fas fa-chart-line fa-3x text-muted mb-3"></i>
                    <h4 class="text-muted">点击左侧热搜话题查看分析结果</h4>
                </div>

                <div id="analysis-content" class="analysis-section">
                    <!-- 加载动画 -->
                    <div id="loading" class="text-center py-5 loading">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-2">正在分析评论数据...</p>
                    </div>

                    <!-- 分析结果 -->
                    <div id="results">
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="mb-0">
                                    <i class="fas fa-chart-pie"></i> 情感分析结果
                                    <span id="topic-title" class="text-primary"></span>
                                </h5>
                                <button id="export-btn" class="btn btn-outline-primary btn-sm">
                                    <i class="fas fa-download"></i> 导出数据
                                </button>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <canvas id="sentiment-chart"></canvas>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="row text-center">
                                            <div class="col-4">
                                                <div class="text-success">
                                                    <h3 id="positive-count">0</h3>
                                                    <small>正面</small>
                                                </div>
                                            </div>
                                            <div class="col-4">
                                                <div class="text-warning">
                                                    <h3 id="neutral-count">0</h3>
                                                    <small>中性</small>
                                                </div>
                                            </div>
                                            <div class="col-4">
                                                <div class="text-danger">
                                                    <h3 id="negative-count">0</h3>
                                                    <small>负面</small>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="card mb-4">
                                    <div class="card-header">
                                        <h5 class="mb-0">
                                            <i class="fas fa-cloud"></i> 关键词云
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div id="keyword-cloud" class="keyword-cloud"></div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="card mb-4">
                                    <div class="card-header">
                                        <h5 class="mb-0">
                                            <i class="fas fa-chart-line"></i> 时间分布
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <canvas id="time-chart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.2/js/bootstrap.bundle.min.js"></script>
    
    <script>
        let sentimentChart = null;
        let timeChart = null;

        // 点击话题事件
        document.querySelectorAll('.topic-card').forEach(card => {
            card.addEventListener('click', function() {
                const topic = this.dataset.topic;
                loadAnalysis(topic);
            });
        });

        // 加载分析数据
        async function loadAnalysis(topic) {
            // 显示加载动画
            document.getElementById('initial-message').style.display = 'none';
            document.getElementById('analysis-content').style.display = 'block';
            document.getElementById('loading').style.display = 'block';
            document.getElementById('results').style.display = 'none';

            try {
                const response = await fetch(`/api/analysis/${encodeURIComponent(topic)}`);
                const data = await response.json();
                
                // 更新UI
                document.getElementById('topic-title').textContent = ` - ${data.topic}`;
                updateSentimentChart(data.sentiments);
                updateKeywordCloud(data.keywords);
                updateTimeChart(data.time_distribution);
                
                // 更新计数
                document.getElementById('positive-count').textContent = data.sentiments.positive;
                document.getElementById('neutral-count').textContent = data.sentiments.neutral;
                document.getElementById('negative-count').textContent = data.sentiments.negative;
                
                // 设置导出按钮
                document.getElementById('export-btn').onclick = () => {
                    window.location.href = `/api/export/${encodeURIComponent(topic)}`;
                };
                
            } catch (error) {
                console.error('Error loading analysis:', error);
                alert('加载数据失败，请重试');
            } finally {
                document.getElementById('loading').style.display = 'none';
                document.getElementById('results').style.display = 'block';
            }
        }

        // 更新情感分析图表
        function updateSentimentChart(sentiments) {
            const ctx = document.getElementById('sentiment-chart').getContext('2d');
            
            if (sentimentChart) {
                sentimentChart.destroy();
            }
            
            sentimentChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: ['正面', '中性', '负面'],
                    datasets: [{
                        data: [sentiments.positive, sentiments.neutral, sentiments.negative],
                        backgroundColor: ['#28a745', '#ffc107', '#dc3545'],
                        borderWidth: 0
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });
        }

        // 更新关键词云
        function updateKeywordCloud(keywords) {
            const container = document.getElementById('keyword-cloud');
            container.innerHTML = '';
            
            const wordList = keywords.map(k => [k.word, k.weight * 100]);
            
            WordCloud(container, {
                list: wordList,
                gridSize: 16,
                weightFactor: 10,
                fontFamily: 'Times, serif',
                color: function(word, weight) {
                    const colors = ['#007bff', '#28a745', '#ffc107', '#dc3545', '#6f42c1'];
                    return colors[Math.floor(Math.random() * colors.length)];
                },
                rotateRatio: 0.5,
                rotationSteps: 2,
                backgroundColor: '#ffffff'
            });
        }

        // 更新时间分布图表
        function updateTimeChart(timeData) {
            const ctx = document.getElementById('time-chart').getContext('2d');
            
            if (timeChart) {
                timeChart.destroy();
            }
            
            const hours = Object.keys(timeData).sort();
            const counts = hours.map(h => timeData[h]);
            
            timeChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: hours.map(h => `${h}:00`),
                    datasets: [{
                        label: '评论数量',
                        data: counts,
                        borderColor: '#007bff',
                        backgroundColor: 'rgba(0, 123, 255, 0.1)',
                        tension: 0.4,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }
    </script>
</body>
</html>
